package com.github.cyf.local;

import com.github.cyf.entity.UploadResult;
import org.apache.commons.io.FilenameUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.UUID;

/**
 * @author chenyifan
 * @create 2025-06-04 9:29
 */
public class LocalUploadUtil {

    /**
     * 文件上传
     * @param multipartFile    上传文件
     * @param fileDir 文件目录
     * @return
     */
    public static UploadResult upload(MultipartFile multipartFile, String fileDir) {
        // 上传的文件
        File dir = new File(fileDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String originalFilename = multipartFile.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        String newFileName = UUID.randomUUID() + "." + extension;
        File file = new File(dir, newFileName);
        // 写入文件
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            throw new UploadException("文件上传失败", e);
        }
        UploadResult uploadResult = new UploadResult();
        uploadResult.setFileName(newFileName);
        uploadResult.setOriginalName(originalFilename);
        uploadResult.setFileType(extension);
        uploadResult.setFilePath(file.getPath());
        uploadResult.setFileSize(file.length());
        return uploadResult;
    }

    /**
     * 文件上传程序、按日期目录进行文件的保存
     * @param file    上传文件
     * @param fileDir 文件保存目录
     * @return 文件路径
     */
    public static UploadResult UploadWithDateDir(MultipartFile file, String fileDir) {
        LocalDate date = LocalDate.now();
        String dateDir = Paths.get(fileDir, String.valueOf(date.getYear()),
                String.format("%02d", date.getMonthValue()),
                String.format("%02d", date.getDayOfMonth())).toString();
        return upload(file, dateDir);
    }

    /**
     * 文件转 MultipartFile
     * @param file
     * @return
     * @throws IOException
     */
    public static MultipartFile transferToMultipartFile(File file) throws IOException {
        FileInputStream is = new FileInputStream(file);
        return new MockMultipartFile(file.getName(), file.getName(), "application/octet-stream", is);
    }
}
